package etc.com.market;

import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import Controls.JsonDataHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import etc.com.sql.DBAdapter;

public class StoreListAct extends Activity implements OnItemClickListener {
	private static final int REQUEST_CODE = 10;

	/** Called when the activity is first created. */
	private ListView lv;
	ArrayList<String> arrtext = new ArrayList<String>();
	ArrayList<String> storeadd = new ArrayList<String>();
	Bitmap[] idimage;
	int[] idimage1;
	String[] strIds;
	Cursor cursor;
	boolean isOldDBVersion = false;
	boolean homeClicked = false;
	boolean specifyClicked = false;
	boolean searchClicked = false;
	boolean infoClicked = false;
	boolean contactClicked = false;
	String storename = "";
	AlertDialog alertDialog;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.storelist);
		Util.enableTouch(this);
		Bundle extras = getIntent().getExtras();
		MarketSystem marketSystem = (MarketSystem) getApplication();
		isOldDBVersion = marketSystem.isOldDBVersion();
		
		if(isOldDBVersion){
			Toast toast = Toast.makeText(this, "Cannot connect to server", Toast.LENGTH_SHORT);
			toast.show();
		}
		String imageStr  = "";
		lv = (ListView) findViewById(R.id.listview);
		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(this);
		lv.setAdapter(new ImageAdapter(this));
		
		
		
		ImageView ImageView = (ImageView) findViewById(R.id.banner);
		ImageView.setImageResource(R.drawable.storebanner);
		
		DBAdapter dbApdapter = new DBAdapter(getApplicationContext());
		cursor = dbApdapter.getAllStore();
		int i = 0;
		idimage = new Bitmap[cursor.getCount()];
		idimage1 = new int[cursor.getCount()];
		strIds = new String[cursor.getCount()];
		while(cursor.moveToNext()){
			String storeName = cursor.getString(1);
			cursor.getColumnNames();
			arrtext.add(storeName);
			String storeAdd = cursor.getString(2);
			storeadd.add(storeAdd);
			String imagePath = cursor.getString(3);
			String imageString = JsonDataHelper.getImageContent(imagePath);
			byte[] decodeBytes = Base64.decode(imageString.getBytes(), Base64.DEFAULT);
			idimage[i] = BitmapFactory.decodeByteArray(decodeBytes, 0, decodeBytes.length);
			idimage1[i] = R.drawable.detail;
			strIds[i] = cursor.getString(0);
			i++;
		}
		
		cursor.close();
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// When clicked, show a toast with the TextView text
				onClick(view, (arrtext.get(position)), strIds[position]);
			}
		});
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
	}
	// function use for footer button ==============================
	public void Previous(View view) {
//		onClick(view, ("Store Info;店舗 A"));
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
		finish();
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
	}

	public void Home(View view) {
		if(!homeClicked){
			Intent i = new Intent(this, StoreListAct.class);
			homeClicked = true;
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);
		}
	}

	public void SearchProduct(View view) {
		onClickSearch(view, "Store Info;店舗 A");
	}

	public void SpecifyProduct(View view) {
		//dialog = ProgressDialog.show(StoreListAct.this.getApplicationContext(), "Loading", "Please wait...", true, false);
		onClickSpec(view, "Store Info;店舗 A" );
	}

	public void Info(View view) {
		onClickInfo(view, "店舗 A");
	}
	
	public void Contact(View view) {
		onClickContact(view, "店舗 A");
	}


	public void onClick(View view, String message, String storeId) {
		alertDialog = new AlertDialog.Builder(StoreListAct.this).create(); //Read Update
        alertDialog.setTitle("Loading");
        alertDialog.setMessage("Please wait");

        alertDialog.show(); 
        
        JSONArray jsonProduct = JsonDataHelper.getJsonObjectFromServer("http://superappli.wacontre.com/web/?target=product&store=" + storeId);
		System.out.println("SIZE: " + jsonProduct.size());
		if( jsonProduct.size() > 0){
			DBAdapter dbAdapter = new DBAdapter(getApplicationContext());
			SQLiteDatabase db = dbAdapter.getDB();
			for(int j = 0; j < jsonProduct.size(); j++){
				JSONObject jsonObj = (JSONObject) jsonProduct.get(j);
				String proId = jsonObj.get("id").toString();
				String proName = jsonObj.get("PRDNM").toString();
				String subTitle = jsonObj.get("SUBTITLE").toString();
				String category = jsonObj.get("CATEGORY").toString();
				String description = jsonObj.get("DSCRPT").toString();
				String vdClip = jsonObj.get("VDCLIP").toString();
				String thumpImg = jsonObj.get("THUMBIMG") == null ? "" : jsonObj.get("THUMBIMG").toString();
				String image = jsonObj.get("IMAGE").toString();
				String upprid = jsonObj.get("UPPRDID").toString();
				dbAdapter.insertProductTable(proId, proName, subTitle, category, description, vdClip, thumpImg, upprid, storeId, image);
			}
			MarketSystem marketSystem = (MarketSystem) getApplication();
			marketSystem.setOldDBVersion(false);
		}else{
			MarketSystem marketSystem = (MarketSystem) getApplication();
			marketSystem.setOldDBVersion(true);
		}
		alertDialog.dismiss();
		// move to next screen
		Intent i = new Intent(getApplicationContext(), StoreTopPage.class);
		i.putExtra("message", message);
		i.putExtra("storeId", storeId);
		startActivity(i);
		overridePendingTransition(R.anim.fadein,
                R.anim.fadeout);
		
	}
	
	public class changeScreenTask extends AsyncTask<String, Integer, Long>{

		@Override
		protected Long doInBackground(String... params) {
			

			JSONArray jsonProduct = JsonDataHelper.getJsonObjectFromServer("http://superappli.wacontre.com/web/?target=product&store=" + params[0]);
			System.out.println("SIZE: " + jsonProduct.size());
			if( jsonProduct.size() > 0){
				DBAdapter dbAdapter = new DBAdapter(getApplicationContext());
				SQLiteDatabase db = dbAdapter.getDB();
				for(int j = 0; j < jsonProduct.size(); j++){
					JSONObject jsonObj = (JSONObject) jsonProduct.get(j);
					String proId = jsonObj.get("id").toString();
					String proName = jsonObj.get("PRDNM").toString();
					String subTitle = jsonObj.get("SUBTITLE").toString();
					String category = jsonObj.get("CATEGORY").toString();
					String description = jsonObj.get("DSCRPT").toString();
					String vdClip = jsonObj.get("VDCLIP").toString();
					String thumpImage = jsonObj.get("THUMBIMG")==null ? "" : jsonObj.get("THUMBIMG").toString();
					String upprid = jsonObj.get("UPPRDID").toString();
					String image = jsonObj.get("IMAGE").toString();
					dbAdapter.insertProductTable(proId, proName, subTitle, category, description, vdClip, thumpImage, upprid, params[0], image);
				}
				MarketSystem marketSystem = (MarketSystem) getApplication();
				marketSystem.setOldDBVersion(false);
			}else{
				MarketSystem marketSystem = (MarketSystem) getApplication();
				marketSystem.setOldDBVersion(true);
			}
			alertDialog.dismiss();
			// move to next screen
			Intent i = new Intent(getApplicationContext(), StoreTopPage.class);
			i.putExtra("message", params[1]);
			i.putExtra("storeId", params[0]);
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);
			return null;
		}
	}
	
	public void onClickSpec(View view, String message) {
		alertDialog = new AlertDialog.Builder(StoreListAct.this).create(); //Read Update
        alertDialog.setTitle("Loading");
        alertDialog.setMessage("Please wait");

        alertDialog.show(); 
		new changeSpecScreenTask().execute(new String[]{message});
	}
	
	public class changeSpecScreenTask extends AsyncTask<String, Integer, Long>{

		@Override
		protected Long doInBackground(String... params) {
			
			JSONArray jsonProduct = JsonDataHelper.getJsonObjectFromServer("http://superappli.wacontre.com/web/?target=product&size=0&type=spec");
			if( jsonProduct.size() > 0){
				DBAdapter dbAdapter = new DBAdapter(getApplicationContext());
				SQLiteDatabase db = dbAdapter.getDB();
				dbAdapter.onCreate(db);
				for(int j = 0; j < jsonProduct.size(); j++){
					JSONObject jsonObj = (JSONObject) jsonProduct.get(j);
					String proId = jsonObj.get("id").toString();
					String proName = jsonObj.get("PRDNM").toString();
					String subTitle = jsonObj.get("SUBTITLE").toString();
					String category = jsonObj.get("CATEGORY").toString();
					String description = jsonObj.get("DSCRPT").toString();
					String vdClip = jsonObj.get("VDCLIP").toString();
					String thmpImg = jsonObj.get("THUMBIMG") == null ? "" : jsonObj.get("THUMBIMG").toString();
					String upprid = jsonObj.get("UPPRDID").toString();
					String image = jsonObj.get("IMAGE").toString();
					dbAdapter.insertProductTable(proId, proName, subTitle, category, description, vdClip, thmpImg, upprid, params[0], image);
				}
				MarketSystem marketSystem = (MarketSystem) getApplication();
				marketSystem.setOldDBVersion(false);
			}else{
				MarketSystem marketSystem = (MarketSystem) getApplication();
				marketSystem.setOldDBVersion(true);
			}
			alertDialog.dismiss();
			// move to next screen
			Intent i = new Intent(getApplicationContext(), ListitemActivity.class);
			i.putExtra("message", params[0]);
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);
			
			return null;
		}
	}
	
	public void onClickSearch(View view, String message) {
			cursor.close();
			Intent i = new Intent(this, SearchOursProducts.class);
			i.putExtra("message", message);
			searchClicked = true;
			// Set the request code to any code you like, you can identify the
			// callback via this code
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);

	}

	public void onClickInfo(View view, String message) {
			cursor.close();
			Intent i = new Intent(this, InfomationAct.class);
			i.putExtra("message", message);
			infoClicked = true;
			// Set the request code to any code you like, you can identify the
			// callback via this code
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);
	}
	
	public void onClickContact(View view, String message) {
			cursor.close();
			Intent i = new Intent(this, SenmailActivity.class);
			i.putExtra("message", message);
			contactClicked = true;
			// Set the request code to any code you like, you can identify the
			// callback via this code
			startActivity(i);
			overridePendingTransition(R.anim.fadein,
	                R.anim.fadeout);
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
			if (data.hasExtra("returnKey1")) {
				Toast.makeText(this, data.getExtras().getString("returnKey1"),
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	public class ImageAdapter extends BaseAdapter {
		private Context mContext;

		public ImageAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			return arrtext.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		// create a new ImageView for each item referenced by the Adapter
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(mContext);

			View row = inflater.inflate(R.layout.row_store_list, parent, false);

			ImageView icon = (ImageView) row.findViewById(R.id.iconfile);
			TextView label = (TextView) row.findViewById(R.id.namefile);
			ImageView detail = (ImageView) row.findViewById(R.id.icondetail);
			


			label.setText(arrtext.get(position));
			// label1.setText(arrtext.get(position));
			icon.setImageBitmap(idimage[position]);
			icon.setScaleType(ScaleType.FIT_XY);
			detail.setImageResource(idimage1[position]);
			
			TextView lbladd = (TextView) row.findViewById(R.id.add);
			lbladd.setText(storeadd.get(position));

			return row;
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}
}
